package com.demo.tool;



import com.demo.bean.NanoFileUpload;
import com.demo.callback.ServerStateCallback;
import com.demo.config.WkConfig;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class WkFileTool {
    private NanoFileUpload nanoFileUploader ;

    private ServerStateCallback serverStateCallback ;
    public WkFileTool( ){

         nanoFileUploader = new NanoFileUpload();
    }

    public void setServerStateCallback(ServerStateCallback serverStateCallback) {
        this.serverStateCallback = serverStateCallback;
    }

    /**
     * 文件上传 。
     */
    public NanoHTTPD.Response fileUpload( NanoHTTPD.IHTTPSession session , ServerTool serverTool ,
                                         List<File> rootDirs, WkHtmlTool wkHtmlTool ) throws FileUploadException, IOException {
        boolean fileExists = false;
        File homeDir = null;

        for (int i = 0;  i <  rootDirs.size(); i++) {
            homeDir =  rootDirs.get(i);
            fileExists = MyBaseFileTool.fileExists(session.getUri(), homeDir);
            if(fileExists){
                break;
            }
        }
        if (!fileExists) {
            return serverTool.render404();
        }
        File reqFile = new File(homeDir.getAbsolutePath() + session.getUri());

        nanoFileUploader.setProgressListener(new ProgressListener() {
            @Override
            public void update(long uploaded, long allSize, int fileNum) {
                float progress = uploaded *100 / (float)allSize ;

                String progressStr =  uploaded+"/"+ allSize+"    "+  progress  +"%" ;
                if(serverStateCallback!=null){
                    serverStateCallback.onFileUploadProgress(progressStr);
                }
            }
        });

        List<FileItem> parseRequest = nanoFileUploader.parseRequest(session);

        for (FileItem fileItem : parseRequest) {
            String fname =fileItem.getName();
            if(fname==null){
                //  个数与实际的数字不一样，原因暂时不明
                continue;
            }

            File tgFile = new File( reqFile.getAbsolutePath() + File.separator + fname );
            InputStream is = fileItem.getInputStream();
            FileOutputStream os = FileUtils.openOutputStream(tgFile, false);

            Streams.copy(is, os, true);
            is.close();
            os.flush();
            os.close();
        }

        WkLog.showLog(" 上传文件 完毕...");
        return  doshowFile(     session ,  serverTool ,  rootDirs,  wkHtmlTool);
    }




    public NanoHTTPD.Response doshowFile(  NanoHTTPD.IHTTPSession session ,
                                         ServerTool serverTool ,List<File> rootDirs,WkHtmlTool wkHtmlTool) {
        Map<String, String> header = session.getHeaders();
        String uri = session.getUri();
        header = Collections.unmodifiableMap(header);// 返回一个不可修改的map
        return serverTool.respond( header , session, uri , rootDirs ,wkHtmlTool ); //doshowFile
    }

    /**
     * 新建文件夹
     */
    public NanoHTTPD.Response makeDir(  NanoHTTPD.IHTTPSession session, Map<String, String> parms ,
                                      List<File> rootDirs , ServerTool serverTool , WkHtmlTool wkHtmlTool ) {
        String value =parms.get(WkConfig.MKDIR);
        String dirName = (value==null|| "".equals(value)) ? "新建文件夹" : value.trim();

        boolean dirExists = false;
        File homeDir = null;
        for (int i = 0;  i <  rootDirs.size(); i++) {
            homeDir =  rootDirs.get(i);
            dirExists = MyBaseFileTool.fileExists(session.getUri(), homeDir);
            if(dirExists){
                break;
            }
        }

        if (!dirExists) {
            return serverTool.render404();
        }

        File tgDir =   new File( homeDir.getAbsolutePath() + session.getUri()  + File.separator + dirName);

        boolean result =tgDir.mkdirs() ;// 创建文件夹
        WkLog.showLog("文件夹创建结果="+ result);
        return doshowFile(  session ,  serverTool ,  rootDirs,  wkHtmlTool);
    }


    /**
     *  删除文件（夹）
     */
    public NanoHTTPD.Response deal_delFile( NanoHTTPD.IHTTPSession session, Map<String, String> parms ,
                                           List<File> rootDirs ,ServerTool serverTool,WkHtmlTool wkHtmlTool) 	throws  IOException {
        boolean isExists = false;
        File homeDir = null;
        for (int i = 0; i <  rootDirs.size(); i++) {
            homeDir =  rootDirs.get(i);
            isExists = MyBaseFileTool.fileExists(session.getUri(), homeDir);
            if(isExists){
                break;
            }
        }
        if (!isExists) {
            return serverTool.render404();
        }

        String delFileName = parms.get(WkConfig.DELETE);
        File tgFile = new File( homeDir.getAbsolutePath() + session.getUri() + File.separator + delFileName );
        boolean result=tgFile.delete() ;
        WkLog.showLog(delFileName+"删除结果："+ result);

        return doshowFile(   session ,  serverTool ,  rootDirs,  wkHtmlTool);
    }

}
